<template>
  <div class="room-reservation-manage">
    <!-- 面包屑和标题 -->
    <el-breadcrumb separator="/" class="mb-2">
      <el-breadcrumb-item>会议管理</el-breadcrumb-item>
      <el-breadcrumb-item>会议室预约管理</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="page-title">会议室预约管理</div>

    <!-- 查询区 -->
    <div class="search-area">
      <el-input v-model="query.RoomName" placeholder="请输入会议名称" clearable style="width: 220px;" />
      <el-button type="primary" @click="onSearch">查询</el-button>
      <el-button @click="onReset">重置</el-button>
      <el-button type="primary" class="new-reservation-btn" @click="onCreateReservation">预约会议</el-button>
    </div>

    <!-- 预约表格 -->
    <el-table :data="tableData" border stripe style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40" />
      <el-table-column prop="Id" label="ID" width="60" />
      <el-table-column prop="MeetingRoomName" label="会议室名称" min-width="120" />
      <el-table-column prop="Subject" label="会议主题" min-width="150" />
      <el-table-column prop="StartTime" label="开始时间" min-width="180">
        <template #default="scope">
          {{ formatDate(scope.row.StartTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="EndTime" label="结束时间" min-width="180">
        <template #default="scope">
          {{ formatDate(scope.row.EndTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="HostName" label="预约人" min-width="100" />
      <el-table-column prop="Status" label="会议状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.Status)">{{ getStatusText(scope.row.Status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="380" fixed="right">
        <template #default="scope">
          <el-button size="small" type="primary" plain @click="onView(scope.row)">
            <el-icon>
              <View />
            </el-icon>会议详情
          </el-button>
          <el-button size="small" type="warning" plain @click="onEdit(scope.row)">
            <el-icon>
              <Edit />
            </el-icon>修改会议
          </el-button>
          <el-button size="small" type="danger" plain @click="onDelete(scope.row)">
            <el-icon>
              <Delete />
            </el-icon>删除
          </el-button>
          <el-button v-if="Number(scope.row.Status) === 5" size="small" type="success" @click="onResubmit(scope.row)">
            重新提交
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <CustomPagination class="mt-2" :currentPage="pageIndex" :pageSize="pageSize" :totalCount="pageInfo.totalCount"
      :totalPage="pageInfo.totalPage" @size-change="onPageSizeChange" @current-change="onCurrentPageChange" />

    <!-- 新建/编辑预约弹窗 -->
    <el-dialog v-model="reservationDialog.visible" :title="reservationDialog.isEdit ? '编辑会议预约' : '新增会议预约'"
      width="900px">
      <el-form :model="reservationForm" label-width="120px" :rules="reservationRules" ref="reservationFormRef">
        <div class="form-section">
          <div class="section-title">基本信息</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="会议模板:" prop="TemplateId">
                <el-select v-model="selectedTemplateId" placeholder="请选择会议模板" @change="onMeetingTemplateChange"
                  clearable>
                  <el-option v-for="template in meetingTemplates" :key="template.id" :label="template.name"
                    :value="template.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="会议主题:" prop="Subject" required>
                <el-input v-model="reservationForm.Subject" placeholder="请输入会议主题" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="会议地点:" prop="MeetingRoomId" required>
                <el-select v-model="reservationForm.MeetingRoomId" placeholder="请选择会议地点" @change="onMeetingRoomChange">
                  <el-option v-for="room in roomOptions" :key="room.Id" :label="room.Name" :value="room.Id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="主持人:" prop="HostName" required>
                <el-input v-model="reservationForm.HostName" placeholder="主持人" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="会议时间:" required>
                <el-date-picker v-model="reservationForm.MeetingDate" type="date" placeholder="请选择日期"
                  value-format="YYYY-MM-DD" style="width: 30%; margin-right: 10px;" />
                <el-time-picker v-model="reservationForm.StartTime" placeholder="开始时间" value-format="HH:mm:ss"
                  style="width: 30%; margin-right: 10px;" />
                <el-time-picker v-model="reservationForm.EndTime" placeholder="结束时间" value-format="HH:mm:ss"
                  style="width: 30%;" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="会议参与人:" prop="Participants">
                <el-input v-model="reservationForm.Participants" placeholder="参与人" type="textarea" :rows="2" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="会议内容:" prop="Content">
                <el-input v-model="reservationForm.Content" placeholder="会议内容" type="textarea" :rows="3" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="form-section mt-4">
          <div class="section-title">会议设置</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="会议签到:" prop="RequireSignIn">
                <el-switch v-model="reservationForm.RequireSignIn" active-text="是" inactive-text="否" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="会议口令:" prop="AccessControlEnabled">
                <el-switch v-model="reservationForm.AccessControlEnabled" active-text="开启" inactive-text="关闭" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="短信通知:" prop="SendSmsNotification">
                <el-switch v-model="reservationForm.SendSmsNotification" active-text="是" inactive-text="否" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否远程会议:" prop="IsRemoteMeeting">
                <el-switch v-model="reservationForm.IsRemoteMeeting" active-text="是" inactive-text="否" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

      </el-form>
      <template #footer>
        <el-button @click="reservationDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="onSaveAsTemplate">保存为模板</el-button>
        <el-button type="primary" @click="onSaveReservation">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="detailDialog.visible" title="会议详情" width="1400px">
      <div class="reservation-detail" v-if="detailDialog.reservation">
        <div class="section-title">基本信息</div>
        <el-row>
          <el-col :span="8">
            <div class="detail-item"><span class="item-label">会议名称：</span>{{ detailDialog.reservation.Subject }}</div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item"><span class="item-label">会议时间：</span>
              {{ formatMeetingTime(detailDialog.reservation.MeetingDate, detailDialog.reservation.StartTime,
                detailDialog.reservation.EndTime) }}
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item"><span class="item-label">会议地点：</span>{{ detailDialog.reservation.MeetingRoomName }}
            </div>
          </el-col>
        </el-row>
        <el-row class="mt-2">
          <el-col :span="24">
            <div class="detail-item">
              <span class="item-label">参会人员：</span>
              <el-tag v-for="(name, idx) in parseParticipants(detailDialog.reservation.Participants)" :key="idx"
                class="mr-1">{{ name }}</el-tag>
            </div>
          </el-col>
        </el-row>
        <el-row class="mt-2">
          <el-col :span="12">
            <div class="detail-item"><span class="item-label">线上地址：</span>
              <a href="https://meeting.example.com/join" target="_blank">https://meeting.example.com/join</a>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item"><span class="item-label">会议电话：</span>
              <span>400-888-9999</span>
            </div>
          </el-col>
        </el-row>
        <div class="section-title mt-3">会议内容</div>
        <div class="detail-item">
          <ol>
            <li v-for="(line, idx) in parseContent(detailDialog.reservation.Content)" :key="idx">{{ line }}</li>
          </ol>
        </div>
        <div class="detail-item mt-2">
          <span class="item-label">会议附件：</span>
          <el-link type="primary" href="#" target="_blank">会议材料.pdf</el-link>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, View, Picture } from '@element-plus/icons-vue' // 引入需要的图标
import CustomPagination from '@/components/CustomPagination.vue'
import {
  getMeetingList,
  addMeeting,
  updateMeeting,
  deleteMeeting,
  batchDeleteMeetings,
  getMeetingDetail,
  type ResubmitMeetingParams
} from '@/api/meetingReservation' // 导入预约管理API
import { approvalResubmit } from '@/api/meetingApproval' // 导入审批重新提交API
import type {
  MeetingListParams,
  MeetingItem,
  MeetingListData,
  MeetingData,
  UpdateMeetingParams
} from '@/api/meetingReservation'
import { getRoomList as getRoomListApi, type RoomItem as RoomItemApi } from '@/api/meetingroom' // 导入会议室列表API和类型
import moment from 'moment' // 导入 moment 用于日期格式化
import { getToken } from '@/utils/auth'
import { useStore } from '@/stores/userInfo'
import type { FormInstance } from 'element-plus'
import axios from 'axios'

// 获取用户信息 - 移到顶部初始化
const store = useStore()

const query = reactive<MeetingListParams>({
  RoomName: '',
  pageIndex: 1,
  pageSize: 10
})

const tableData = ref<MeetingItem[]>([])
const selectedReservations = ref<MeetingItem[]>([]) // 用于批量操作

const pageIndex = ref(1)
const pageSize = ref(10)
const pageInfo = reactive({
  totalCount: 0,
  totalPage: 1
})

const reservationFormRef = ref()

// 会议预约表单数据类型
interface ReservationFormType {
  Id: number;
  Subject: string;
  MeetingRoomId: number;
  MeetingRoomName: string;
  HostId: string;
  HostName: string;
  MeetingDate: string;
  StartTime: string;
  EndTime: string;
  Participants: string;
  Content: string;
  RequireSignIn: boolean;
  AccessControlEnabled: boolean;
  SendSmsNotification: boolean;
  IsRemoteMeeting: boolean;
  Status: number;
  UserId: string; // 用户ID字段，改为string类型
}

const selectedTemplateId = ref<number | null>(null); // 用于绑定会议模板下拉框选择的值

// 先确保store中的值已经初始化
const getUserId = () => {
  return store.userinfo?.userid ? String(store.userinfo.userid) : '2'
}

const getUserName = () => {
  return store.userinfo?.realname || 'admin'
}

const reservationForm = reactive<ReservationFormType>({
  Id: 0,
  Subject: '',
  MeetingRoomId: 0,
  MeetingRoomName: '',
  HostId: getUserId(), // 使用函数获取用户ID
  HostName: getUserName(), // 使用函数获取用户名
  MeetingDate: '',
  StartTime: '',
  EndTime: '',
  Participants: '',
  Content: '',
  RequireSignIn: false,
  AccessControlEnabled: false,
  SendSmsNotification: false,
  IsRemoteMeeting: false,
  Status: 0, // 默认待开始状态
  UserId: getUserId(), // 使用函数获取用户ID
})

// 表单校验规则
const reservationRules = reactive({
  Subject: [{ required: true, message: '请输入会议主题', trigger: 'blur' }],
  MeetingRoomId: [{ required: true, message: '请选择会议室', trigger: 'change' }],
  HostName: [{ required: true, message: '请输入主持人', trigger: 'blur' }],
  MeetingDate: [{ required: true, message: '请选择会议日期', trigger: 'change' }],
  StartTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  EndTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  Participants: [{ required: true, message: '请输入会议参与人', trigger: 'blur' }],
  Content: [{ required: true, message: '请输入会议内容', trigger: 'blur' }],
})

// 会议室选项
const roomOptions = ref<RoomItemApi[]>([])

// 会议模板选项，现在直接写死，后续可能从API获取
const meetingTemplates = ref([
  { id: 1, name: '标准会议室模板', subject: '标准会议', participants: '参会人员1,参会人员2', content: '标准会议内容', requireSignIn: true, accessControlEnabled: false, sendSmsNotification: true, isRemoteMeeting: false },
  { id: 2, name: '高级会议室模板', subject: '高级会议', participants: '参会人员A,参会人员B', content: '高级会议内容', requireSignIn: true, accessControlEnabled: true, sendSmsNotification: true, isRemoteMeeting: true },
  { id: 3, name: '小型讨论室模板', subject: '小型讨论', participants: '参会人员X,参会人员Y', content: '小型讨论内容', requireSignIn: false, accessControlEnabled: false, sendSmsNotification: false, isRemoteMeeting: false },
])

// 弹窗状态
const reservationDialog = reactive({
  visible: false,
  isEdit: false,
})

const detailDialog = reactive({
  visible: false,
  reservation: null as MeetingItem | null,
})

// 选中行
const multipleSelection = ref<MeetingItem[]>([])

// 添加一个变量标记组件是否已挂载
const isMounted = ref(false)

// 格式化日期时间
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  return moment(dateString).format('YYYY-MM-DD HH:mm:ss')
}

// 获取状态标签类型
const getStatusTagType = (status: number) => {
  switch (status) {
    case 0: return 'info' // 待审核
    case 1: return 'warning' // 进行中
    case 2: return 'success' // 已结束
    case 3: return 'danger' // 已取消
    case 4: return '' // 待开始
    case 5: return 'danger' // 已驳回
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 0: return '待审核'
    case 1: return '进行中'
    case 2: return '已结束'
    case 3: return '已取消'
    case 4: return '待开始'
    case 5: return '已驳回'
    default: return '未知'
  }
}

// 解析参与人字符串
const parseParticipants = (participantsStr: string) => {
  return participantsStr ? participantsStr.split(',').filter(p => p.trim() !== '') : []
}

// 解析会议内容字符串
const parseContent = (contentStr: string) => {
  return contentStr ? contentStr.split('\n').filter(p => p.trim() !== '') : []
}

// 获取会议列表
const fetchMeetingList = async () => {
  if (!isMounted.value) return // 如果组件未挂载，不执行操作
  
  try {
    const response = await getMeetingList({
      pageIndex: query.pageIndex,
      pageSize: query.pageSize,
      RoomName: query.RoomName,
    })
    if (response.Data) {
      tableData.value = response.Data.Data
      pageInfo.totalCount = response.Data.TotalCount
      pageInfo.totalPage = response.Data.TotalPage
    } else {
      tableData.value = []
      pageInfo.totalCount = 0
      pageInfo.totalPage = 0
    }
  } catch (error) {
    console.error('获取会议列表失败:', error)
    tableData.value = []
    pageInfo.totalCount = 0
    pageInfo.totalPage = 0
    ElMessage.error('获取会议列表失败')
  }
}

// 查询
const onSearch = () => {
  query.pageIndex = 1
  fetchMeetingList()
}

// 重置
const onReset = () => {
  query.RoomName = ''
  query.pageIndex = 1
  fetchMeetingList()
}

// 创建预约
const onCreateReservation = () => {
  reservationDialog.isEdit = false
  resetForm(reservationFormRef.value)
  // 初始化表单数据为默认值，这里根据后端实体字段的默认值进行设置
  Object.assign(reservationForm, {
    Id: 0,
    Subject: '',
    MeetingRoomId: 0,
    MeetingRoomName: '',
    HostId: getUserId(), // 使用函数获取用户ID
    HostName: getUserName(), // 使用函数获取用户名
    MeetingDate: '',
    StartTime: '',
    EndTime: '',
    Participants: '',
    Content: '',
    RequireSignIn: false,
    AccessControlEnabled: false,
    SendSmsNotification: false,
    IsRemoteMeeting: false,
    Status: 0, // 默认待开始状态
    UserId: getUserId(), // 使用函数获取用户ID
  })
  selectedTemplateId.value = null; // 重置模板选择
  reservationDialog.visible = true
}

// 视图会议详情
const onView = async (row: MeetingItem) => {
  // 直接使用当前行数据
  detailDialog.reservation = { ...row };
  detailDialog.visible = true;
}

// 编辑会议
const onEdit = (row: MeetingItem) => {
  reservationDialog.isEdit = true
  Object.assign(reservationForm, {
    ...row,
    // 后端返回的是DateTime字符串，前端日期选择器需要Date对象或特定格式的字符串
    MeetingDate: moment(row.MeetingDate).format('YYYY-MM-DD'),
    StartTime: moment(row.StartTime).format('HH:mm:ss'),
    EndTime: moment(row.EndTime).format('HH:mm:ss'),
    // 确保id是number类型
    Id: Number(row.Id),
  })
  // 如果有MeetingRoomName，根据name找到对应的MeetingRoomId
  const selectedRoom = roomOptions.value.find(room => room.Name === row.MeetingRoomName)
  if (selectedRoom) {
    reservationForm.MeetingRoomId = selectedRoom.Id
  }
  selectedTemplateId.value = null; // 编辑时不带入模板选择
  reservationDialog.visible = true
}

// 删除会议
const onDelete = (row: MeetingItem) => {
  ElMessageBox.confirm('确定删除该会议预约吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const token = getToken()

        const response = await deleteMeeting(row.Id);


        ElMessage.success('删除成功')
        fetchMeetingList()


      } catch (error) {
        console.error('删除会议失败:', error)
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 批量删除
const onBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的会议预约')
    return
  }

  ElMessageBox.confirm('确定批量删除选中的会议预约吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const idsToDelete = multipleSelection.value.map(item => item.Id)
        const token = getToken()
        if (!token) {
          ElMessage.error('未获取到用户认证信息，请重新登录。')
          return
        }

        const headers = { Authorization: `Bearer ${token}` }
        const response = await axios.delete('BaseDataWriteAPI/Meeting/BatchDeleteMeetings', {
          headers,
          data: { meetingIds: idsToDelete }, // DELETE请求携带body数据需要放在data字段
        })


      } catch (error) {
        console.error('批量删除会议失败:', error)
        ElMessage.error('批量删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消批量删除')
    })
}

// 保存会议预约 (新增/编辑)
const onSaveReservation = async () => {
  if (!reservationFormRef.value) return

  reservationFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 构建要发送到后端的数据
        const meetingDateMoment = moment(reservationForm.MeetingDate);
        const startTimeOnlyMoment = moment(reservationForm.StartTime, 'HH:mm:ss');
        const endTimeOnlyMoment = moment(reservationForm.EndTime, 'HH:mm:ss');

        const combinedStartTime = meetingDateMoment.clone()
          .hour(startTimeOnlyMoment.hour())
          .minute(startTimeOnlyMoment.minute())
          .second(startTimeOnlyMoment.second())
          .format('YYYY-MM-DDTHH:mm:ss');

        const combinedEndTime = meetingDateMoment.clone()
          .hour(endTimeOnlyMoment.hour())
          .minute(endTimeOnlyMoment.minute())
          .second(endTimeOnlyMoment.second())
          .format('YYYY-MM-DDTHH:mm:ss');

        const formattedMeetingDate = meetingDateMoment.format('YYYY-MM-DDTHH:mm:ss');

        const dataToSend = {
          ...reservationForm,
          MeetingDate: formattedMeetingDate,
          StartTime: combinedStartTime,
          EndTime: combinedEndTime,
          MeetingRoomName: roomOptions.value.find(room => room.Id === reservationForm.MeetingRoomId)?.Name || '',
          HostId: getUserId(), // 使用函数获取用户ID
          HostName: getUserName(), // 使用函数获取用户名
          Status: reservationForm.Status, // 保持现有状态或根据需求设置
          UserId: getUserId(), // 使用函数获取用户ID
        }

        if (reservationDialog.isEdit) {
          await updateMeeting(dataToSend as UpdateMeetingParams)
          ElMessage.success('会议预约更新成功')
        } else {
          await addMeeting(dataToSend)
          ElMessage.success('会议预约新增成功')
        }
        reservationDialog.visible = false
        fetchMeetingList()
      } catch (error: any) {
        console.error('保存会议预约失败:', error)
        if (error.response) {
          console.error('后端响应错误数据:', error.response.data)
          ElMessage.error(error.response.data.Msg || '保存会议预约失败');
        } else {
          ElMessage.error('保存会议预约失败: ' + error.message || '未知错误');
        }
      }
    }
  })
}

// 会议模板变更
const onMeetingTemplateChange = (templateId: number) => {
  const selectedTemplate = meetingTemplates.value.find(t => t.id === templateId);
  if (selectedTemplate) {
    Object.assign(reservationForm, {
      Subject: selectedTemplate.subject,
      Participants: selectedTemplate.participants,
      Content: selectedTemplate.content,
      RequireSignIn: selectedTemplate.requireSignIn,
      AccessControlEnabled: selectedTemplate.accessControlEnabled,
      SendSmsNotification: selectedTemplate.sendSmsNotification,
      IsRemoteMeeting: selectedTemplate.isRemoteMeeting,
    });
    // 清空会议室选择，让用户重新选择
    reservationForm.MeetingRoomId = 0;
    reservationForm.MeetingRoomName = '';
    // 重新设置主持人信息为当前登录用户
    reservationForm.HostName = getUserName(); // 设置主持人为当前用户姓名，如果没有则默认为"admin"
    reservationForm.HostId = getUserId(); // 设置主持人ID为字符串类型的用户ID
  } else {
    // 如果取消选择模板，重置部分字段
    reservationForm.Subject = '';
    reservationForm.Participants = '';
    reservationForm.Content = '';
    reservationForm.RequireSignIn = false;
    reservationForm.AccessControlEnabled = false;
    reservationForm.SendSmsNotification = false;
    reservationForm.IsRemoteMeeting = false;
  }
};

// 会议室选择变更 (保留，因为MeetingRoomId和MeetingRoomName需要同步)
const onMeetingRoomChange = (roomId: number) => {
  const selectedRoom = roomOptions.value.find(room => room.Id === roomId)
  if (selectedRoom) {
    reservationForm.MeetingRoomName = selectedRoom.Name
  }
}

// 页面大小改变
const onPageSizeChange = (size: number) => {
  query.pageSize = size
  fetchMeetingList()
}

// 当前页改变
const onCurrentPageChange = (current: number) => {
  query.pageIndex = current
  fetchMeetingList()
}

// 处理表格多选
const handleSelectionChange = (val: MeetingItem[]) => {
  multipleSelection.value = val
}

// 重置表单校验
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

onMounted(() => {
  isMounted.value = true
  fetchMeetingList()
  fetchRoomOptions()
})

// 获取会议室列表用于下拉框
const fetchRoomOptions = async () => {
  if (!isMounted.value) return // 如果组件未挂载，不执行操作
  
  try {
    const response = await getRoomListApi({
      pageIndex: 1,
      pageSize: 1000, // 获取所有会议室
    })
    if (response.Data) {
      roomOptions.value = response.Data.Data.map(room => ({
        ...room // 将RoomItem的所有属性展开
      }))
    } else {
      roomOptions.value = []
    }
  } catch (error) {
    console.error('获取会议室列表失败:', error)
    ElMessage.error('获取会议室列表失败')
  }
}

// 保存为模板功能
const onSaveAsTemplate = () => {
  ElMessage.info('保存为模板功能待实现，请联系后端开发。')
  console.log('保存为模板', reservationForm)
  // 在这里，您通常会调用一个API来将当前表单数据保存为新模板。
  // 示例: addMeetingTemplate(reservationForm)
}

// 格式化会议时间
const formatMeetingTime = (date: string, startTime: string, endTime: string) => {
  if (!date || !startTime || !endTime) return '时间未设置';

  try {
    const formattedDate = moment(date).format('YYYY-MM-DD');
    const formattedStartTime = moment(startTime).format('HH:mm');
    const formattedEndTime = moment(endTime).format('HH:mm');
    return `${formattedDate} ${formattedStartTime} - ${formattedEndTime}`;
  } catch (error) {
    console.error('格式化会议时间出错:', error);
    return `${date} ${startTime} - ${endTime}`;
  }
}

// 重新提交会议申请
const onResubmit = (row: MeetingItem) => {
  ElMessageBox.confirm(
    '确定要重新提交此会议申请吗？',
    '重新提交确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        // 显示加载提示
        ElMessage({
          message: '正在提交...',
          type: 'info'
        });

        // 调用重新提交接口
        const response = await approvalResubmit(row.Id);

        // 处理响应
        ElMessage.success('重新提交成功');
        fetchMeetingList(); // 重新加载列表
      } catch (error: any) {
        console.error('重新提交失败:', error);
        ElMessage.error(error.message || '重新提交失败');
      }
    })
    .catch(() => {
      // 用户取消操作
      ElMessage.info('已取消重新提交');
    });
}
</script>

<style scoped>
.room-reservation-manage {
  padding: 24px;
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 18px;
}

.search-area {
  margin-bottom: 18px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.new-reservation-btn {
  margin-left: auto;
}

/* 详情弹窗样式 */
.reservation-detail {
  padding: 10px;
}

.detail-item {
  display: flex;
  margin-bottom: 10px;
}

.item-label {
  font-weight: bold;
  width: 120px;
  color: #606266;
}

.item-value {
  flex: 1;
  color: #303133;
}

.equipment-tag {
  margin-right: 5px;
}

.detail-image-small {
  width: 100px;
  height: 75px;
  border-radius: 4px;
  object-fit: cover;
}

/* 会议室图片上传样式 */
.room-image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 90px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.room-image-uploader:hover {
  border-color: #409EFF;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}
</style>